<?php


namespace App\Services\Admin;


use App\Http\Controllers\Api\RemoteApiRoute;
use App\Models\Asin;
use App\Models\Product;
use Illuminate\Support\Facades\Http;
use MongoDB\BSON\ObjectId;

class ProductService
{
    public function __construct()
    {

    }

    /**
     * 根据ASIN获取产品信息
     * @param $params
     * @return \Illuminate\Http\Client\Response|\Illuminate\Http\JsonResponse
     */
    public function getProductByAsin($params){
        $products = Product::whereIn('asin',$params['asins'])->orderBy('sales_rank_current','asc')->get();

        //本地无产品信息请求服务器
        if (!count($products)){
            $url = env('REMOTE_API_URL') . RemoteApiRoute::PRODUCT_INFO;
            $response = Http::post($url, ['domainId' => (int)$params['domainId'], 'asins' => $params['asins']]);
            if ($response->ok()){
                $products = $response->json()['result'];
                Product::insert($products);
            }else{
                return Error($response->reason());
            }
        }

        //更新asin已获取
        Asin::whereIn('asin',$params['asins'])->update(['has_info' => 1]);

        return Success('ok', $products);
    }

    /**
     * @param $params
     * @return \Illuminate\Http\JsonResponse
     */
    public function getProductInfo($params){
        $where = array();
        $where['created_at'] = ['$gt' => 0];
        $pageSize = $params['pageSize'];

        if (isset($params['domainId'])){
            $where['domainId'] = (int)$params['domainId'];
        }
        if (isset($params['task_id'])){
            $where['client_task_id'] = $params['task_id'];
        }
        if (isset($params['star_level'])){
            $where['star_level'] = (int)$params['star_level'];
        }
        if (isset($params['asin'])){
            $where['asin'] = trim($params['asin']);
        }
        if (isset($params['category'])){
            $where['categories'] = trim($params['category']);
        }
        if (isset($params['buy_box_current'])){
            if (isset($params['buy_box_current'][0]) && $params['buy_box_current'][0] !== ''){
                $where['buy_box_current']['$gte'] = trim($params['buy_box_current'][0]);
            }
            if (isset($params['buy_box_current'][1]) && $params['buy_box_current'][1] !== ''){
                $where['buy_box_current']['$lte'] = trim($params['buy_box_current'][1]);
            }
        }
        if (isset($params['reviews_rating'])){
            if (isset($params['reviews_rating'][0]) && $params['reviews_rating'][0] !== ''){
                $where['reviews_rating']['$gte'] = trim($params['reviews_rating'][0]);
            }
            if (isset($params['reviews_rating'][1]) && $params['reviews_rating'][1] !== ''){
                $where['reviews_rating']['$lte'] = trim($params['reviews_rating'][1]);
            }
        }
        if (isset($params['reviews_review_count'])){
            if (isset($params['reviews_review_count'][0]) && $params['reviews_review_count'][0] !== ''){
                $where['reviews_review_count']['$gte'] = (int)$params['reviews_review_count'][0];
            }
            if (isset($params['reviews_review_count'][1]) && $params['reviews_review_count'][1] !== ''){
                $where['reviews_review_count']['$lte'] = (int)$params['reviews_review_count'][1];
            }
        }
        if (isset($params['sales_rank_current'])){
            if (isset($params['sales_rank_current'][0]) && $params['sales_rank_current'][0] !== ''){
                $where['sales_rank_current']['$gte'] = (int)$params['sales_rank_current'][0];
            }
            if (isset($params['sales_rank_current'][1]) && $params['sales_rank_current'][1] !== ''){
                $where['sales_rank_current']['$lte'] = (int)$params['sales_rank_current'][1];
            }
        }
        $skip = ((int)$params['page'] - 1) * $pageSize;

        $products = Product::select('asin', 'task_id', 'imagesCSV', 'categories', 'title', 'sales_rank_current', 'domainId', 'manufacturer', 'categoryTree', 'reviews_rating', 'reviews_review_count', 'buy_box_current', 'created_at', 'star_level', 'mark_remark')->where($where)->limit($pageSize)->skip($skip)->orderBy('created_at','desc')->get();
        $total = Product::where($where)->count();

        if (count($products)){
            foreach ($products as $product){
                $images = array();
                $image_arr = explode(',',$product->imagesCSV);
                foreach ($image_arr as $image){
                    $images[] = env('AMAZON_ASSET_URL').$image;
                }
                $product->image_arr = $images;
            }
            return Success('ok', ['items' => $products, 'total' => $total]);
        }else{
            return Error('暂无产品信息！',$where);
        }
    }

    /**
     * 获取产品详情
     * @param $params
     * @return \Illuminate\Http\JsonResponse
     */
    public function getProductDetail($params){
        $where = array();
        $where['domainId'] = $params['domainId'];
        $where['asin'] = $params['asin'];

        $product = Product::where($where)->first();

        $images = array();
        $image_arr = explode(',',$product->imagesCSV);
        foreach ($image_arr as $image){
            $images[] = env('AMAZON_ASSET_URL').$image;
        }
        $product->image_arr = $images;
        $product->update_time = date('Y-m-d H:i:s', $product->created_at);
        $product->lastPriceChange = date('Y-m-d H:i:s', $product->lastPriceChange);

        if ($product){
            return Success('ok', $product);
        }else{
            return Error('暂无该产品信息！');
        }
    }

    /**
     * 删除产品
     * @param $params
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteProduct($params){
        $res = Product::where('_id',$params['_id'])->delete();
        if ($res){
            return Success('ok', $res);
        }else{
            return Error('删除失败，请稍后重试！');
        }
    }

    /**
     * 标记产品
     * @param $params
     * @return \Illuminate\Http\JsonResponse
     */
    public function markProduct($params){
        if (!$params['star_level']){
            return Error('标记失败，请选择推荐星级！');
        }
        if (isset($params['mark_remark'])){
            $mark_remark = $params['mark_remark'];
        }else{
            $mark_remark = '';
        }

        $where = ['domainId' => (int)$params['domainId'], 'asin' => $params['asin']];
        $update = ['star_level' => (int)$params['star_level'], 'mark_remark' => $mark_remark, 'mark_time' => time()];
        $res = Product::where($where)->update($update);

        if ($res){
            return Success('ok', $res);
        }else{
            return Error('标记失败，请稍后重试！',-1,[$where, $update]);
        }

    }

    /**
     * 获取ASIN信息
     * @param $params
     * @return \Illuminate\Http\Client\Response|\Illuminate\Http\JsonResponse
     */
    public function getAsinInfo($params){
        $page = isset($params['page'])?$params['page']:1;
        $pageSize = isset($params['pageSize'])?$params['pageSize']:100;
        $where = array();
        $where['create_time'] = ['$gt' => 0];
        if (isset($params['domainId'])){
            $where['domainId'] = (int)$params['domainId'];
        }
        if (isset($params['asin'])){
            $where['asin'] = $params['asin'];
        }
        if (isset($params['catId'])){
            $where['catId'] = (int)$params['catId'];
        }
        if (isset($params['has_info'])){
            if ($params['has_info']){
                $where['has_info'] = (int)$params['has_info'];
            }else{
                $where['has_info'] = ['$exists' => false];
            }
        }

        $skip = ((int)$page - 1) * 100;
        $asins = Asin::where($where)->limit($pageSize)->skip($skip)->get();
        $total = Asin::where($where)->count();
        $result = [
            'items' => $asins,
            'total' => $total
        ];
        return Success('ok', $result);
    }

    /**
     * 导出表格
     * @param $params
     * @return \Illuminate\Http\JsonResponse
     */
    public function exportXls($params){
        $where_str = '';
        foreach ($params as $k => $v){
            if ($v !== ''){
                if (in_array($k,['star_level', 'domainId'])){
                    $where_str .= $k.'='.(int)$v.',';
                }elseif(in_array($k,['buy_box_current', 'reviews_rating', 'reviews_review_count', 'sales_rank_current'])){
                    $where_str .= $k.'='.implode('~',$v).',';
                }else{
                    $where_str .= $k.'='.$v.',';
                }
            }
        }

        $pythonScriptPath = base_path('app/PythonScripts/wt_export.py'); // 脚本的完整路径
        exec("python {$pythonScriptPath} " . $where_str . " 2>&1", $out, $res);
        if ($res == 0){
            return Success('ok', $out[0]);
        }else{
            return Error('导出失败，请稍后重试！',$res,$out);
        }
    }
}
